import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * Computer Network, Programming Assignment #2
 * 
 * Thread for handling packets form other peers
 * @author Yancheng Li
 *
 */

public class PeerThread extends Thread{
	private Socket	peerSocket;
	private Point pos;	
	private BufferedReader in = null;// 
	private DataOutputStream out = null;//
	private PGPeer peer = null;
	
	public PeerThread(Socket peerSocket, PGPeer peer, Point pos){
		this.peerSocket = peerSocket;
		this.pos = pos;
		this.peer = peer;
	
		try {
			in = new BufferedReader(new InputStreamReader(peerSocket.getInputStream()));
			out = new DataOutputStream(peerSocket.getOutputStream());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	
	}
	
	public void run(){
		char[] data = new char[2048];
		char[] num = new char[4];
		try {
			while(true)
			{
				int readLength = in.read(data, 0, 4);
				
				if(readLength <= 0)
					break;
				for(int i = 0; i < 4; i++)
					num[i] = data[i];						
				
				int length = Integer.parseInt(new String(num), 16);
				//System.out.println("Peer " + pos + " read data length = " + length);
				//System.out.println(">>");
				in.read(data, 4, length - 4);			
				
				GPDatagram packet = new GPDatagram(data);
				
				PSPUtil.print("Peer " + pos + " got packet \n" + packet, peer.getPrint());
				peer.sendPacket(packet);
				
				Thread.sleep(100);
			}
			
			PSPUtil.print("Peer thread of " + pos + "exit", peer.getPrint());
						
		} catch (Exception e) {
			e.printStackTrace();			
		}		
	}
}
